import {BASE_URL,HEADER} from '../config.js'
//设置session_id
const getSid = function(vm) {
	let session = vm.$util.getDb('session');	
	if (!session) {
		let guid = vm.$u.guid();		
		vm.$util.setDb('session', guid);
		return guid;
	}
	return session;
}
const install = (Vue, vm) => {
	Vue.prototype.$u.http.setConfig({
		baseUrl: BASE_URL,
		originalData: true,
		header:HEADER
	});
	Vue.prototype.$u.http.interceptor.request = (config) => {
		config.data = config.data || {}
		config.header.token = vm.vuex_token
		config.header.sid = getSid(vm);
		config.header.uid = vm.vuex_user.id || 0;
		return config;
	}
	// 响应拦截
	Vue.prototype.$u.http.interceptor.response = (response) => {
		const data = response.data
		if(data.code === 0){
			return data
		}else if(data.code === 401){
			vm.$u.vuex('vuex_token', '')
			vm.$u.vuex('vuex_user', '')
			vm.$Router.push('/pages/login/login')
			return data;
		}else if(data.code === 403){
			uni.showToast({
				icon: "none",
				title: data.msg
			})
			return data;
		}else{
			if (response.statusCode == 200) {
				return data;
			} else {
				vm.$u.toast('网络错误');
			}
		}
	}
}
export default {
	install
}
